package com.jplus.mvc;

import com.jplus.core.core.abstracts.defaults.DefaultEnvironment;
import com.jplus.core.mvc.servlet.DispatcherServlet;
import com.jplus.core.utill.JUtil;
import com.jplus.mvc.web.WebConfig;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.undertow.Handlers;
import io.undertow.Undertow;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.PathHandler;
import io.undertow.servlet.Servlets;
import io.undertow.servlet.api.DeploymentInfo;
import io.undertow.servlet.api.DeploymentManager;

public class Application {
	private static final Logger log = LoggerFactory.getLogger(Application.class);

	public static void main(String[] args) {
		// String ac = System.getProperty("ansicolor");
		// if (ac != null && ac.equalsIgnoreCase("ENABLE"))
		// AnsiOutput.setEnabled(Enabled.ALWAYS);// 强制开启日志色彩
		int port = args.length >= 1 ? Integer.parseInt(args[0]) : 0;
		String path = args.length >= 2 ? args[1] : "/";
		String host = args.length == 3 ? args[2] : "127.0.0.1";
		// ===============================================
		if (port == 0) {
			DefaultEnvironment auto = DefaultEnvironment.getSingleton();
			port = JUtil.toInt(auto.getProp("server.port"));
			path = auto.getProp("server.context-path");
		}
		if (port == 0)
			log.error(
					"\n>>Place the configuration file in the classpath [app.properties/application.properties] and insert:"
							+ "\nserver.port=8080\r\n" + "server.context-path=/xxx" + ""
							+ "\n\n>>Or set the main function input and execute CMD:"
							+ "\njava -jar xxx.jar 8080 /xxx");
		else
			new Application().initUndertow(port, host, path, WebConfig.class);

	}

	public void initUndertow(int port, String host, String contextPath, Class<?> contextConfigLocation) {
		try {
			DeploymentInfo servletBuilder = Servlets.deployment().setClassLoader(getClass().getClassLoader())
					.setContextPath(contextPath).setDeploymentName(contextPath.replaceAll("/", ""))
					.addServlet(Servlets.servlet("DispatcherServlet", DispatcherServlet.class)
							.addInitParam("contextConfigLocation", contextConfigLocation.getName()).addMapping("/")
							.setLoadOnStartup(1).setAsyncSupported(true));

			DeploymentManager manager = Servlets.defaultContainer().addDeployment(servletBuilder);
			manager.deploy();

			HttpHandler httpHandler = manager.start();
			PathHandler pathHandler = Handlers.path();
			pathHandler.addPrefixPath(contextPath, httpHandler);

			Undertow.Builder build = Undertow.builder();
			build.addHttpListener(port, host);
			build.setHandler(pathHandler);
			build.setWorkerThreads(9);
			build.build().start();
			log.info("Starter Undertow with port:{},context-path:{},host:{}  OK!!", port, contextPath, host);
			log.info("Access to the address= http://{}:{}{}", host, port, contextPath);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

}
